<template>
  <!-- 服务分类管理 -->
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-del="false"
        @add="add"
        @cancel="cancel"
        @del="del"
        @edit="edit"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">用户名:</div>
          <div class="input">
            <el-input v-model="searchForm.nickName" clearable @keyup.enter.native="search" @blur="search" @clear="search" />
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">用户账号:</div>
          <div class="input">
            <el-input v-model="searchForm.omUserName" clearable @keyup.enter.native="search" @blur="search" @clear="search" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <!-- 业务组件展示表格 -->
      <div class="zh-table-view">
        <el-table
          :data="tableData"
          height="100%"
          @row-click="handleEdit"
        >
          <el-table-column
            type="index"
            width="50"
          />
          <el-table-column
            prop="nickName"
            label="用户名"
          />
          <el-table-column
            prop="omUserName"
            label="用户账号"
          />
          <el-table-column
            prop="phone"
            label="手机号"
          />
          <el-table-column
            prop="expire"
            label="启用状态"
          >
            <template slot-scope="scope">
              <el-switch v-model="scope.row.expire" :active-value="true" :inactive-value="false" active-text="启用"
                inactive-text="停用" @change="editStatus(scope.row)" active-color="#13ce66" inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="500">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="editRole(scope.row)"
              >角色分配</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="edit"
              >修改名称</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="editPassword(scope.row)"
              >修改密码</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="dellineallmes(scope.$index, scope.row)"
              >删除</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="reset(scope.$index, scope.row)"
              >重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :page-size="pageSize"
          :current-page="currentPage"
          :total-size="totalSize"
          @changePageSize="changePageSize"
          @changeCurrentPage="changeCurrentPage"
        />
      </div>
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '账号'"
        class="formData"
        :visible.sync="dialogFormVisible"
        width="40%"
        :before-close="() => { cancel() }"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <template v-if="nowChanceStau == 'add'">
            <el-form-item label="账号:" prop="omUserName" class="w100p">
              <el-input v-model="formData.omUserName" placeholder="请输入账号" clearable />
            </el-form-item>
            <el-form-item label="密码:" prop="password" class="w100p">
              <el-input
                v-model="formData.password"
                show-password
                type="password"
                autocomplete="new-password"
                placeholder="请输入密码"
              />
            </el-form-item>
            <el-form-item label="确认密码:" prop="passwordtwo" class="w100p">
              <el-input
                v-model="formData.passwordtwo"
                show-password
                type="password"
                autocomplete="new-password"
                placeholder="请再次输入密码"
              />
            </el-form-item>
          </template>
          <el-form-item label="用户名:" prop="nickName" class="w100p">
            <el-input v-model="formData.nickName" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item v-if="nowChanceStau == 'add'" label="手机号:" prop="phone" class="w100p">
            <el-input v-model="formData.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog
        :title="dialogRoleTitle"
        class="formData"
        :visible.sync="dialogRoleVisible"
        width="40%"
        :before-close="() => { cancelRole() }"
      >
        <el-form
          ref="form"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <template v-if="dialogRoleTitle == '角色分配'">
            <el-checkbox-group v-model="checkedRole" class="sub-check">
              <el-checkbox
                v-for="(data, indexs) in roleList"
                :key="indexs"
                :label="data.roleNo"
                :disabled="data.status === '1'"
              >
                {{ data.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
          <template v-if="dialogRoleTitle == '修改密码'">
            <el-form-item label="原密码:" prop="oldPassword" class="w100p">
              <el-input
                v-model="formData.oldPassword"
                show-password
                type="password"
                autocomplete="new-password"
                placeholder="请输入原密码"
              />
            </el-form-item>
            <el-form-item label="新密码:" prop="newPassword" class="w100p">
              <el-input
                v-model="formData.newPassword"
                show-password
                type="password"
                autocomplete="new-password"
                placeholder="请输入新密码"
              />
            </el-form-item>
            <el-form-item label="确认密码:" prop="newPasswordtwo" class="w100p">
              <el-input
                v-model="formData.newPasswordtwo"
                show-password
                type="password"
                autocomplete="new-password"
                placeholder="请再次输入密码"
              />
            </el-form-item>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelRole()">取 消</el-button>
          <el-button type="primary" @click="saveRole">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar/index";
import { mymixin } from "@/utils/mixins";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SelectButton from "@/components/SelectButton";
import Pagination from "@/components/Pagination";
import userApi from "@/api/agricultural-social/system-manage/user-manage.js";
import roleApi from "@/api/agricultural-social/system-manage/role-manage.js";
export default {
  components: { ActionBar, BaseMainSlot, Pagination, SearchBox, SelectButton },
  mixins: [mymixin],
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码不得小于六位"));
      } else if (value !== this.formData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    const validatePassword2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码不得小于六位"));
      } else {
        callback();
      }
    };
    const validatePassword3 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码不得小于六位"));
      } else if (value !== this.formData.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      pageSize: 10,
      currentPage: 1,
      totalSize: 0,
      // ---添加相关---
      formData: {},
      checkedRole: [],
      searchForm: {},
      rules: {
        nickName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        omUserName: [{ required: true, message: "请输入账号", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: ["blur", "change"] },
          {
            pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
            message: "请输入合法的手机号",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, validator: validatePassword2, trigger: "blur" },
          { required: true, message: "请输入密码", trigger: "blur" }
        ],
        passwordtwo: [
          { required: true, validator: validatePassword, trigger: "blur" },
          { required: true, message: "请再次输入密码", trigger: "blur" }
        ],
        oldPassword: [
          { required: true, validator: validatePassword2, trigger: "blur" },
          { required: true, message: "请输入原密码", trigger: "blur" }
        ],
        newPassword: [
          { required: true, validator: validatePassword2, trigger: "blur" },
          { required: true, message: "请输入新密码", trigger: "blur" }
        ],
        newPasswordtwo: [
          { required: true, validator: validatePassword3, trigger: "blur" },
          { required: true, message: "请再次输入密码", trigger: "blur" }
        ],
      },
      dialogRoleVisible: false,
      dialogRoleTitle: '',
      roleList: [],
    };
  },
  watch: {
    dialogFormVisible (v) {
      if (v && this.titleText == '添加') {
        this.checkList = ['终端用户方可用', '服务提供方可用']
      }
    }
  },
  mounted () {
    this.queryRole()
    this.gettabledataList()
  },
  methods: {
    queryRole () {
      roleApi.queryPageByCondition({
        page: 1,
        size: 1000,
      }).then(res => {
        if (res.code == 1) {
          this.roleList = res.data.content
        } else {
          this.roleList = []
        }
      })
    },
    cancelRole () {
      this.dialogRoleVisible = false
    },
    editRole (data) {
      this.checkedRole = []
      this.form = {
        ...data
      }
      this.checkedRole = data.omRoles ? data.omRoles.map(el => { return el.roleNo }) : []
      this.dialogRoleTitle = '角色分配'
      this.dialogRoleVisible = true
    },
    saveRole () {
      if (this.dialogRoleTitle == '修改密码') {
        this.$refs.form.validate((valid) => {
          if (valid) {
            userApi.changePassword({
              omUserNo: this.formData.omUserNo,
              oldPassword: this.formData.oldPassword,
              newPassword: this.formData.newPassword
            }).then(res => {
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                this.cancelRole()
                this.gettabledataList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg || '操作失败!'
                })
              }
            })
          }
        });
      } else {
        let param = `?usernames=${this.form.omUserName}`
        this.checkedRole.map(el => {
          param += `&roleNos=${el}`
        })
        userApi.bindUser(param).then(res => {
          if (res.code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.cancelRole()
            this.gettabledataList()
          } else {
            this.$message({
              type: 'info',
              message: res.msg || '操作失败!'
            })
          }
        })
      }
    },
    // 获取表格信息
    async gettabledataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchForm,
        }
      };
      userApi.queryPageByCondition(params).then(res => {
        console.log(res)
        if (res.code == 1) {
          this.tableData = res.data.content || []
          this.totalSize = res.data.totalElements
          this.resetActionBar()
        } else {
          this.$message.warning("获取表格失败")
        }
      })
    },
    handleSelectionChange() {
      this.nowselectedList = [];
      const list = this.$refs.catetreetwo.getCheckedNodes();
      this.nowselectedList = list.map((item) => {
        return item.id;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.gettabledataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.gettabledataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.gettabledataList();
    },
    editPassword (row) {
      this.dialogRoleTitle = '修改密码'
      this.dialogRoleVisible = true
      this.formData = {
        ...row
      }
    },
    // 修改
    handleEdit(row) {
      if (row) {
        this.formData = {
          ...row
        }
      }
    },
    reset (i, e) {
      this.$confirm('此操作将重置该用户密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.resetPassword(e.omUserNo).then(res => {
          if (res.code == 1) {
            this.$message.success(res.msg)
            this.gettabledataList()
          }
        })
      })
    },
    // 删除一个业务组件
    dellineallmes(i, e) {
      this.$confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.delListByNo({
          noList: [e.omUserNo]
        }).then(res => {
          if (res.code == 1) {
            this.$message.success("删除成功！")
            this.gettabledataList()
          }
        })
      })
    },
    // 保存要添加的业务的组件信息
    save() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          let param = {
            ...this.formData,
          }
          userApi[this.nowChanceStau](param).then(res => {
            if (res.code == 1) {
              this.$message.success(res.msg || "操作成功！")
              this.gettabledataList()
              this.dialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          return false;
        }
      });
    },
    //修改用户状态
    editStatus (data) {
      this.$confirm('您确定要修改该角色的状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.updateExpire(data.omUserId, data.expire).then(res => {
          if (res.code == 1) {
            this.gettabledataList()
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          } else {
            data.expire = !data.expire
            this.$message({
              type: 'info',
              message: res.msg
            });
          }
        })
      }).catch(() => {
        data.expire = !data.expire
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
      });
    },
  }
};
</script>

<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  .business-main{
  width: 100%;
  height: 100%;
  .topbar-view{
    width: 100%;
    margin-bottom: 5px;
  }
  .zh-table-view{
    width: 100%;
    height: calc(100% - 60px);
    position: relative;
  }
}
.add-components-dia {
  width: 502px;
  // height: 191px;
  background: #303640;
  border: 1px solid #005c6f;
  border-radius: 7px;
  position: fixed;
  top: 15%;
  left: 40%;
  // background-color: #005c6f;
  z-index: 99;
  .top-bar {
    width: 502px;
    height: 10px;
    background: linear-gradient(90deg, #3581fb 0%, #00faad 100%);
    border-radius: 7px 7px 0px 0px;
  }
  .top-title-line {
    width: 490px;
    height: 35px;
    line-height: 35px;
    padding: 6px 8px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #484a4e;
    .line-title {
      height: 20px;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: $textColor;
      letter-spacing: 2px;
    }
    .line-close {
      color: #10d7c4;
      cursor: pointer;
    }
    .line-close:hover {
      color: $textColor;
    }
  }
  .screen-dia-main {
    width: 502px;
    padding: 20px 10px;
    // max-height: 550px;
    overflow-y: auto;
    overflow-x: hidden;
    max-height: 480px;
    .title-config{
      padding-bottom: 20px;
      border-bottom: #00faad 1px solid;
      margin-bottom: 10px;
    }
    .dia-main-inputline {
      width: 482px;
      margin-top: 5px;
      display: flex;
      // justify-content: center;
      align-items: center;
      margin-bottom: 10px;
      .inputline-name {
        width: 120px;
        height: 24px;
        font-size: 16px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: $textColor;
        line-height: 24px;
        text-align: center;
      }
      .inputline-value {
        width: 350px;
        height: 32px;
        box-sizing: border-box;
        border-radius: 0px 0px 0px 0px;
        opacity: 1;
        border: 1px solid #494e57;
        box-sizing: border-box;
        outline: 0;
      }
      .textarealine-value {
        width: 350px;
        height: 32px;
        box-sizing: border-box;
        border-radius: 0px 0px 0px 0px;
        opacity: 1;
        border: 1px solid #494e57;
        box-sizing: border-box;
        outline: 0;
      }
      .icon-line-value {
        width: 48px;
        height: 48px;
        text-align: center;
        .not-iconurl {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }
        .not-iconurl:hover {
          border-color: #1caf7e;
        }
        .not-iconsty {
          font-size: 20px;
          color: #8c939d;
          width: 48px;
          height: 48px;
          line-height: 48px;
          text-align: center;
        }
      }
      .selcect-one {
        width: 350px;
        height: 32px;
        box-sizing: border-box;
        border-radius: 0px 0px 0px 0px;
        opacity: 1;
        border: 1px solid #494e57;
        box-sizing: border-box;
        outline: 0;
      }
    }
    .dia-main-addline {
      width: 442px;
      font-size: 16px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: $textColor;
      line-height: 24px;
      border-bottom: #00faad 1px dashed;
      padding-bottom: 16px;
      margin-bottom: 10px;
      .components-line {
        display: flex;
        // justify-content: space-between;
        align-items: center;
        width: 442px;
        height: 48px;
        .slect-name {
          width: 90px;
          height: 36px;
          font-size: 16px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: $textColor;
          line-height: 36px;
          text-align: center;
        }
        .selcect-one {
          width: 350px;
          color: #00faad;
          margin-top: 12px;
          height: 36px;
          line-height: 36px;
          background-color: transparent;
          border: #00faad dashed 1px;
          cursor: pointer;
          option {
            background-color: #005c6f !important;
            color: $textColor;
            cursor: pointer;
          }
        }
      }
      .addline-but {
        width: 442px;
        display: flex;
        justify-content: space-around;
        margin-top: 15px;
        .addline-but1 {
          color: #00faad;
          border: 1px solid #00faad;
          cursor: pointer;
          padding: 5px 10px;
        }
        .addline-but1:hover {
          color: $textColor;
        }
        .addline-but2 {
          color: #3581fb;
          border: 1px solid #3581fb;
          cursor: pointer;
          padding: 5px 10px;
        }
        .addline-but2:hover {
          color: $textColor;
        }
      }
    }
    .dia-main-addline:last-of-type {
      padding-bottom: 0;
      margin: 0;
      border: none;
    }
    .showkuang-one {
      position: relative;
      left: 41px;
      width: 400px;
      min-height: 200px;
      .kuangone-main {
        position: absolute;
        width: 100%;
        height: 400px;
      }
    }
  }
  .bottom-bar {
    width: 482px;
    height: 50px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    font-size: 16px;
    .bottom-bar-cancel {
      width: 96px;
      height: 33px;
      border-radius: 5px 5px 5px 5px;
      border: 1px solid #0cb9ae;
      color: #0cb9ae;
      cursor: pointer;
      line-height: 33px;
      text-align: center;
    }
    .bottom-bar-cancel:hover {
      color: #00faad;
    }
    .bottom-bar-confirm {
      width: 96px;
      height: 33px;
      background: #0cb9ae;
      border-radius: 5px 5px 5px 5px;
      cursor: pointer;
      line-height: 33px;
      text-align: center;
    }
    .bottom-bar-confirm:hover {
      color: #10fab4;
    }
  }
}
::v-deep .el-switch__label {
  color: #fff !important;

  &.is-active {
    color: #409EFF !important;
  }
}
::v-deep {
  .el-dialog {
    min-width: 35% !important;
  }
  .el-tree-node__label {
    color: #000;
  }
}
.search-list {
  .common-search-item {
    .label {
      min-width: 80px !important;
      text-align: right;
    }
  }
}
</style>
